const router = require('koa-router')()

async function isLogin(ctx, next) {
  if (!ctx.session.user) {
    ctx.flash = { warning: '未登录，请先登录' }
    return ctx.redirect('/signin')
  }
  await next()
}

async function isAdmin(ctx, next) {
  if (!ctx.session.user.isAdmin) {
    ctx.flash = { warning: '没有权限' }
    return ctx.redirect('back')
  }
  await next()
}

module.exports = (app) => {
  router.get('/', require('./home').index)
  
  router.get('/signup', require('./user').signup)
  router.post('/signup', require('./user').signup)

  router.get('/signin', require('./user').signin)
  router.post('/signin', require('./user').signin)

  router.get('/signout', require('./user').signout)

  // 写文章
  router.get('/create', isLogin, isAdmin, require('./article').create)
  router.post('/create', isLogin, isAdmin, require('./article').create)
  router.get('/detail/:id', require('./article').detail)


  app
    .use(router.routes())
    .use(router.allowedMethods())
}